#include "ipsetdlg.h"
#include "ui_ipsetdlg.h"

IPSetDlg::IPSetDlg(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::IPSetDlg)
{
    ui->setupUi(this);
    setWindowTitle("确认IP");

    QRegExp IPRegx("((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)");
    QRegExp portRegx("[0-9]{5}");

    ui->IPLineEdit->setValidator(new QRegExpValidator(IPRegx, ui->IPLineEdit));
    ui->portLineEdit->setValidator(new QRegExpValidator(portRegx, ui->portLineEdit));

}

IPSetDlg::~IPSetDlg()
{
    delete ui;
}

QString IPSetDlg::getHostAddr()
{
    return this->hostAddr;
}

unsigned short IPSetDlg::getPort()
{
    return this->port;
}

void IPSetDlg::on_okBtn_clicked()
{
    this->hostAddr = ui->IPLineEdit->text();
    this->port = ui->portLineEdit->text().toUShort();

    if(this->hostAddr.isNull() | (this->port == 0)){
        QMessageBox::critical(this, "错误", "请填写IP和端口号信息", QMessageBox::Ok);
        this->hostAddr.clear();
        this->port = 0;
        ui->IPLineEdit->clear();
        ui->portLineEdit->clear();
        return ;
    }
    else {
        logger.setIpAndPort(this->hostAddr, this->port);
        logger.writeLog(Logger::IPChanged);
        emit(IPChanged(hostAddr, port));
        this->close();
    }
}

//void IPSetDlg::on_cancelBtn_clicked()
//{
//    if(this->hostAddr.isNull() | (this->port == 0))
//        QMessageBox::critical(this, "错误", "未找到先前填写的IP地址和端口号,请填写后确认", QMessageBox::Ok);
//}

//void IPSetDlg::closeEvent(QCloseEvent *event)
//{
//    if(this->hostAddr.isNull() | (this->port == 0)){
//        QMessageBox::critical(this, "错误", "请检查IP地址和端口号输入", QMessageBox::Ok);
//        event->ignore();
//    }
//    else {
//        this->close();
//    }
//}

